<?php

namespace App\Jobs;

use zgldh\QiniuStorage\QiniuStorage;
use QL\QueryList;
use Illuminate\Support\Facades\DB;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class DigArticleChinaz implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $article;
    protected $col;

    public function __construct($article,$col)
    {
        $this->article  = $article;
        $this->col      = $col;
    }

    public function handle()
    {
        $data    = $this->check($this->article['link']);
        if($data){
            $index  = $this->ithome($data);
            if($index){
                $content = DB::table('articles')->where('title', $index['title'])->first();
                if($content)
                {
                    return true;
                }
                $id = DB::table('articles')->insertGetId([
                    'column_id'     => $this->col,
                    'title'         => $index['title'],
                    'copy_from'     => $index['copy_from'],
                    'keywords'      => $index['keywords'],
                    'description'   => $index['description'],
                    'content'       => $index['content'],
                    'views'         => 0,
                    'state'         => 1,
                    'created_at'    => date('Y-m-d H:i:s',time()),
                    'updated_at'    => date('Y-m-d H:i:s',time()),
                ]);
                if($id){
                    $this->ziyuan($id);
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    public function ithome($data){
    	$ql = QueryList::html($data)->rules([
            //采集规则
            'title'         => ['.article-header .title','text'],
            'keywords'      => ['meta[name=keywords]','content'],
            'description'   => ['meta[name=description]','content'],
            'content'       => ['#article-content','html'],
        ])->query()->getData(function ($item) {
            //利用回调函数下载文章中的图片并替换图片路径为本地路径
            //使用本例请确保当前目录下有image文件夹，并有写入权限
            $item['keywords']		= str_replace(' ', ',', $item['keywords']);
            $item['copy_from']		= '本站原创|#';
            $content = QueryList::html($item['content']);
            $content->find('img')->map(function($img){
                $src = $img->attr('src');
                $localSrc = 'article/images/'.md5($src).'.jpg';
				//文件是否存在
                $disk = QiniuStorage::disk('qiniu');
                if(!$disk->exists($localSrc)){
                    $contents   = $this->check($src);
                    if($contents){
                        $disk->put($localSrc,$contents); //上传文件
                    }
                }
                $img->attr('class', 'load');
                $img->attr('lay-src', env('IMG_URL').$localSrc);
                $img->attr('src', env('IMG_URL').'files/loading.gif');
            });
            $content->find('blockquote')->remove();
            $content->find('div')->remove();
            $item['content']    = $content->find('')->html();
            return $item;
        });
        $data   = $ql->all();
        if($data){
            return $data;
        }else{
            return false;
        }
    }
    //抓取网址
    function check($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//抓取网址
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Baiduspider/3.0; +http://www.baidu.com/search/spider.html)");//伪造百度蜘蛛头部
        $ip = '220.181.7.121';
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $ip, 'CLIENT-IP:' . $ip));//伪造百度蜘蛛IP
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//
//        curl_setopt($ch, CURLOPT_HEADER, true); //抓取服务器信息
        curl_setopt($ch, CURLOPT_NOBODY, false); //抓取网页信息
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //支持301跳转
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30); //网页等待时间
        $data = curl_exec($ch);
        $code = curl_getinfo($ch);
        curl_close($ch);
        if($code['http_code'] == 200){
            return $data;
//            $parse_url  = parse_url($code['url']);
//            return      $parse_url['scheme'].'://'.$parse_url['host'];
        }else{
            return false;
        }
    }

    function ziyuan($id)
    {
        $urls = [
            env('APP_URL').'/artinfo-'.$id.'.html',
        ];
        $api = env('BAIDUZHANZHANG');
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
    
    function xiongzhanghao($id)
    {
    	$urls = array(
		    env('APP_URL').'/artinfo-'.$id.'.html',
		);
		$api = env('XZH');
		$ch = curl_init();
		$options =  array(
		    CURLOPT_URL => $api,
		    CURLOPT_POST => true,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_POSTFIELDS => implode("\n", $urls),
		    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		return $result;
    }
}
